"""
LSTM 编码解码
"""

import random
import torch
from torch import nn
import torch.nn.functional as f
from pytorch_pretrained_bert import BertModel,BertTokenizer,BertConfig,BertAdam
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
                              TensorDataset)
import torch.optim as optim
import numpy as np


SEED = 4321
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)


def get_train_data(tokenizer):
    seq_len = 64
    example_pair_list = []
    # 数据
    input_text = "[CLS] 我今天心情很好[SEP] "
    target_text = "今天天气怎么样"

    example_pair = dict()

    tokenized_text = tokenizer.tokenize(input_text)
    # for i in target_text:
    #     tokenized_text.append('[MASK]')
    # # tokenized_text.append('[SEP]')
    for _ in range(seq_len - len(tokenized_text)):  # 不足128的全部补 【mask】
        tokenized_text.append('[PAD]')
    # tokenized_text.append('[MASK]')
    indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)

    # tokens_tensor = torch.tensor([indexed_tokens]).to(device)

    loss_ids = []
    loss_ids.append(tokenizer.convert_tokens_to_ids(['[CLS]'])[0])
    for i in target_text:
        loss_ids.append(tokenizer.convert_tokens_to_ids(i)[0])
    loss_ids.append(tokenizer.convert_tokens_to_ids(['[SEP]'])[0])
    for _ in range(seq_len - len(loss_ids)):  # 拼接长度为  128  后面的数据补-1
        loss_ids.append(0)
    # loss_tensors = torch.tensor([loss_ids]).to(device)

    # segment_ids = []
    segment_ids = [0]*seq_len

    example_pair['tokens'] = indexed_tokens
    example_pair['loss'] = loss_ids
    example_pair['segment_ids'] = segment_ids
    example_pair_list.append(example_pair)
    example_pair_list.append(example_pair)


    all_input_ids = torch.tensor([f['tokens'] for f in example_pair_list], dtype=torch.long)
    all_segment_ids = torch.tensor([f['segment_ids'] for f in example_pair_list], dtype=torch.long)
    all_labels = torch.tensor([f['loss'] for f in example_pair_list], dtype=torch.long)
    dataset = TensorDataset(all_input_ids, all_segment_ids, all_labels)

    # example_pair[tokens_tensor] = loss_tensors
    return dataset


class Encoder(nn.Module):
    def __init__(self, input_dim, emb_dim, hid_dim, n_layers, dropout):
        super().__init__()

        self.hid_dim = hid_dim
        self.n_layers = n_layers

        self.embedding = nn.Embedding(input_dim, emb_dim)

        self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout)

        self.dropout = nn.Dropout(dropout)

    def forward(self, src):
        # src = [src len, batch size]

        embedded = self.dropout(self.embedding(src))
        # embedded = [src len, batch size, emb dim]

        outputs, (hidden, cell) = self.rnn(embedded)
        # outputs = [src len, batch size, hid dim * n directions]
        # hidden = [n layers * n directions, batch size, hid dim]
        # cell = [n layers * n directions, batch size, hid dim]

        # outputs are always from the top hidden layer
        return hidden, cell


class Decoder(nn.Module):
    def __init__(self, output_dim, emb_dim, hid_dim, n_layers, dropout):
        super().__init__()

        self.output_dim = output_dim
        self.hid_dim = hid_dim
        self.n_layers = n_layers

        self.embedding = nn.Embedding(output_dim, emb_dim)

        self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout)

        self.fc_out = nn.Linear(hid_dim, output_dim)

        self.dropout = nn.Dropout(dropout)

    def forward(self, input, hidden, cell):
        # input = [batch size]
        # hidden = [n layers * n directions, batch size, hid dim]
        # cell = [n layers * n directions, batch size, hid dim]

        # n directions in the decoder will both always be 1, therefore:
        # hidden = [n layers, batch size, hid dim]
        # context = [n layers, batch size, hid dim]

        input = input.unsqueeze(0)
        # input = [1, batch size]

        embedded = self.dropout(self.embedding(input))
        # embedded = [1, batch size, emb dim]

        output, (hidden, cell) = self.rnn(embedded, (hidden, cell))
        # output = [seq len, batch size, hid dim * n directions]
        # hidden = [n layers * n directions, batch size, hid dim]
        # cell = [n layers * n directions, batch size, hid dim]

        # seq len and n directions will always be 1 in the decoder, therefore:
        # output = [1, batch size, hid dim]
        # hidden = [n layers, batch size, hid dim]
        # cell = [n layers, batch size, hid dim]

        prediction = self.fc_out(output.squeeze(0))
        # prediction = [batch size, output dim]

        return prediction, hidden, cell


class Seq2Seq(nn.Module):
    def __init__(self, encoder, decoder, device):
        super().__init__()

        self.encoder = encoder
        self.decoder = decoder
        self.device = device

        assert encoder.hid_dim == decoder.hid_dim, \
            "Hidden dimensions of encoder and decoder must be equal!"
        assert encoder.n_layers == decoder.n_layers, \
            "Encoder and decoder must have equal number of layers!"

    def forward(self, src, trg, teacher_forcing_ratio=0.5):
        # src = [src len, batch size]
        # trg = [trg len, batch size]
        # teacher_forcing_ratio is probability to use teacher forcing
        # e.g. if teacher_forcing_ratio is 0.75 we use ground-truth inputs 75% of the time

        batch_size = trg.shape[1]
        trg_len = trg.shape[0]
        trg_vocab_size = self.decoder.output_dim

        # tensor to store decoder outputs
        outputs = torch.zeros(trg_len, batch_size, trg_vocab_size).to(self.device)

        # last hidden state of the encoder is used as the initial hidden state of the decoder
        hidden, cell = self.encoder(src)

        # first input to the decoder is the <sos> tokens
        input = trg[0, :]

        for t in range(1, trg_len):
            # insert input token embedding, previous hidden and previous cell states
            # receive output tensor (predictions) and new hidden and cell states
            output, hidden, cell = self.decoder(input, hidden, cell)

            # place predictions in a tensor holding predictions for each token
            outputs[t] = output

            # decide if we are going to use teacher forcing or not
            teacher_force = random.random() < teacher_forcing_ratio

            # get the highest predicted token from our predictions
            top1 = output.argmax(1)

            # if teacher forcing, use actual next token as next input
            # if not, use predicted token
            input = trg[t] if teacher_force else top1

        return outputs


def init_weights(m):
    for name, param in m.named_parameters():
        nn.init.uniform_(param.data, -0.08, 0.08)


tokenizer = BertTokenizer.from_pretrained(r'D:\work\deep_learning_model\chinese_wwm_ext_pytorch')

vocab_size = len(tokenizer.vocab)
INPUT_DIM = vocab_size
OUTPUT_DIM = vocab_size
ENC_EMB_DIM = 512
DEC_EMB_DIM = 512
HID_DIM = 512
N_LAYERS = 2
ENC_DROPOUT = 0.5
DEC_DROPOUT = 0.5

enc = Encoder(INPUT_DIM, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT)
dec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, N_LAYERS, DEC_DROPOUT)

device = torch.device('cuda')

model = Seq2Seq(enc, dec, device)

model.apply(init_weights)

model.to(device)


def train_model(model, train_dataset, clip=1):

    train_sampler = RandomSampler(train_dataset)
    train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=2)

    optimizer = optim.Adam(model.parameters())
    model.train()

    epoch = 50
    for _ in range(epoch):
        epoch_loss = 0
        for i, batch in enumerate(train_dataloader):
            batch = tuple(t.to(device) for t in batch)
            src = batch[0]
            trg = batch[2]
            output = model(src,trg)
            # trg = [trg len, batch size]
            # output = [trg len, batch size, output dim]

            output_dim = output.shape[-1]

            output = output[1:].view(-1, output_dim)
            trg = trg[1:].view(-1)
            # trg = [(trg len - 1) * batch size]
            # output = [(trg len - 1) * batch size, output dim]
            criterion = nn.CrossEntropyLoss(ignore_index=0)
            loss = criterion(output, trg)
            epoch_loss += loss.item()
            loss.backward()
            optimizer.step()
            model.zero_grad()
            torch.nn.utils.clip_grad_norm_(model.parameters(), clip)
        print(epoch_loss/(i+1))

train_dataset = get_train_data(tokenizer)
train_model(model, train_dataset)



# 9.952091217041016
# 9.849266052246094
# 9.742242813110352
# 9.612296104431152
# 9.468107223510742
# 9.285758972167969
# 9.017574310302734
# 8.6368989944458
# 8.17296314239502
# 7.4229254722595215
# 6.479736328125
# 5.167126178741455
# 3.709632396697998
# 2.928964138031006
# 2.570659637451172
# 2.1252517700195312
# 1.7012213468551636
# 1.5380046367645264
# 1.5912429094314575
# 1.5501596927642822
# 1.516053318977356
# 1.4471185207366943
# 1.3007456064224243
# 1.0208654403686523
# 0.7640454769134521
# 0.5912243723869324
# 0.40752124786376953